package com.ysy.logistics.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ysy.common.resp.ResultData;
import com.ysy.logistics.entities.system.MenuNode;
import com.ysy.logistics.entities.system.RoleMenu;
import com.ysy.logistics.myannotation.OperateLog;
import com.ysy.logistics.service.system.MenuNodeService;
import com.ysy.logistics.service.system.RoleMenuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassDescription:
 * @Author:姚斯羽
 * @Create:2025/3/19 17:32
 **/
@Slf4j
@RestController
@RequestMapping(value = "/sysMenu", name = "菜单")
@Tag(name = "菜单管理", description = "sys_menu表的CRUD")
@CrossOrigin
public class MenuNodeController {

    @Resource
    private MenuNodeService menuNodeService;
    @Resource
    private RoleMenuService roleMenuService;

    @GetMapping(value = "/list")
    public ResultData list() {
        log.info("获取菜单列表");
        return ResultData.success(menuNodeService.getMenus());
    }

    @PostMapping(value = "/add")
    @OperateLog("添加菜单")
    public ResultData add(@RequestBody MenuNode menuNode) {
        log.info("添加菜单：{}", menuNode);
        boolean isNewAdd = Objects.isNull(menuNode.getId());
        //菜单编码是否存在
        LambdaQueryWrapper<MenuNode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MenuNode::getCode, menuNode.getCode());
        if (!isNewAdd) {
            queryWrapper.ne(MenuNode::getId, menuNode.getId());
        }
        if (menuNodeService.exists(queryWrapper)) {
            return ResultData.fail("菜单编码已存在");
        }
        queryWrapper.clear();
        queryWrapper.eq(MenuNode::getUrl, menuNode.getUrl());
        if (!isNewAdd) {
            queryWrapper.ne(MenuNode::getId, menuNode.getId());
        }
        if (menuNodeService.exists(queryWrapper)) {
            return ResultData.fail("菜单路径已存在");
        }
        if (StringUtils.equalsIgnoreCase("layout", menuNode.getComponent())){
           menuNode.setComponent("Layout");
        }
        //是否有父节点
        menuNode.setParentId(0L);
        if (StringUtils.isNotEmpty(menuNode.getPcode())) {
            LambdaQueryWrapper<MenuNode> lqw = new LambdaQueryWrapper<>();
            lqw.select(MenuNode::getId).eq(MenuNode::getCode, menuNode.getPcode());
            MenuNode one = menuNodeService.getOne(lqw);
            if (Objects.nonNull(one)) {
                menuNode.setParentId(one.getId());
            }
        }
        //存在ID更新
        if (!isNewAdd) {
            menuNodeService.updateById(menuNode);
        } else {
            menuNodeService.save(menuNode);
        }

        return ResultData.success();
    }

    @GetMapping(value = "/getMenuTree")
    @Operation(summary = "获取菜单树")
    public ResultData getMenuTree() {
        return ResultData.success(menuNodeService.getMenuTree());
    }

    @GetMapping(value = "/delete/{id}")
    @Operation(summary = "通过id删除菜单")
    @OperateLog("删除菜单")
    public ResultData delete(@PathVariable("id") Long id) {
        log.info("删除菜单：{}", id);
        menuNodeService.clearById(id);
        return ResultData.success();
    }

    @GetMapping(value = "/getRoleMenuTree/{id}")
    @Operation(summary = "获取角色菜单树")
    public ResultData getRoleMenuTree(@PathVariable("id") String id) {
        log.info("获取角色菜单树：{}", id);
        //查询角色菜单
        LambdaQueryWrapper<RoleMenu> lqw = new LambdaQueryWrapper<>();
        lqw.select(RoleMenu::getMenuId)
                .eq(RoleMenu::getRoleId, id);
        List<RoleMenu> menus = roleMenuService.list(lqw);
        List<Long> menuIds = menus.stream().map(RoleMenu::getMenuId).collect(Collectors.toList());
        Map<String,Object> result = new HashMap<>();
        result.put("checkedKeys", menuIds);
        result.put("treeData", menuNodeService.getRoleMenuTree(menuIds));
        return ResultData.success(result);
    }

}
